嗨,我是 A Fei,讓我們看看今天的題目:
(題目來源:Codewars)
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:
[] --> "no one likes this"
["Peter"] --> "Peter likes this"
["Jacob", "Alex"] --> "Jacob and Alex like this"
["Max", "John", "Mark"] --> "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"] --> "Alex, Jacob and 2 others like this"
以下是我的答案:
def likes(names)
case names.size
when 0
"no one likes this"
when 1
"#{names[0]} likes this"
when 2
"#{names[0]} and #{names[1]} like this"
when 3
"#{names[0]}, #{names[1]} and #{names[2]} like this"
else
"#{names[0]}, #{names[1]} and #{names.size - 2} others like this"
end
end
當同一種狀況要判斷很多次時,可以用 case
... when
,讓你的 code 更簡潔易懂。不過要注意的是,在 case
... when
裡面我們是用 === 去判斷是否相等,而不是 if
... else
常用的 ==。
由於和最高分解答一模一樣,這次就不解析了。